import React, { useEffect, useState } from "react";
import NavBar from "@/components/NavBar/NavBar";
import { useNavigate } from "react-router-dom";
import { Button, Form, Image, Input, Toast } from "antd-mobile";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import { fetchGraphCodeThunk, fetchMobileCodeThunk, loginThunk } from "@/store/modules/loginStore";
import type { GraphCode, LoginForm } from "@/type/LoginType";
import useCountdown from "@/hooks/useCountdown";
import "./Login.scss";

const Login = () => {
   const navigate = useNavigate();
   const { start, countdown, subCountdown } = useCountdown(10);

   const enhanceDispatch = useEnhanceDispatch();

   const [formInstance] = Form.useForm();

   const graphCode: GraphCode = useEnhanceSelector(state => state.loginStore.graphCode);

   const [loading, setLoading] = useState<boolean>(false);
   /**
    * 获取图形验证码的回调函数
    * */
   const fetchGraphCode = async () => {
      try {
         await enhanceDispatch(fetchGraphCodeThunk()).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * @description 点击获取验证码按钮的回调函数
    * */
   const getMobileCode = async () => {
      const validate = await formInstance.validateFields(["mobile", "captchaCode"]).catch(error => error);
      if ("outOfDate" in validate) return;
      subCountdown();
      if (start) {
         Toast.show("验证码获取频繁");
         return;
      }
      try {
         const captchaCode: string = formInstance.getFieldValue("captchaCode");
         const mobile: string = formInstance.getFieldValue("mobile");
         const data = { captchaCode, mobile, captchaKey: graphCode.key };
         await enhanceDispatch(fetchMobileCodeThunk(data)).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };


   /**
    * @description 提交表单且数据验证成功后触发
    * */
   const onFinish = async (values: LoginForm) => {
      try {
         setLoading(true);
         const loginParams = { isParty: false, partyData: {}, mobile: values.mobile, smsCode: values.smsCode };
         await enhanceDispatch(loginThunk(loginParams)).unwrap();
         navigate("/");
         Toast.show({ icon: "success", content: "登录成功" });
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      } finally {
         setLoading(false);
      }
   };


   /**
    * @description 提交表单且数据验证失败后触发
    * */
   const onFinishFailed = ({ errorFields }: { errorFields: any }) => {
      Toast.show(errorFields[0].errors[0]);
   };

   useEffect(() => {
      fetchGraphCode();
   }, []);

   return (
      <div className="login-container">
         <NavBar children="会员登录" backIcon onBack={() => navigate(-1)}></NavBar>
         <div className="login-main">
            <div className="header">
               <span className="title">手机号登录</span>
               <span className="tip">未注册的手机号登录后将自动注册</span>
            </div>
            <Form hasFeedback={false} mode="card" form={formInstance} onFinish={onFinish} onFinishFailed={onFinishFailed}>
               <Form.Item className="first" name="mobile" rules={[{ required: true, message: "请输入手机号" }]}>
                  <Input placeholder="请输入手机号"></Input>
               </Form.Item>
               <Form.Item name="captchaCode" rules={[{ required: true, message: "请输入图形验证码" }]} extra={<Image src={graphCode.base64} onClick={() => fetchGraphCode()} />}>
                  <Input placeholder="请输入图形验证码"></Input>
               </Form.Item>
               <Form.Item name="smsCode" rules={[{ required: true, message: "请输入短信验证码" }]} extra={<Button color="primary" size="small" onClick={getMobileCode}>{start ? `${countdown}S后重新获取` : "获取验证码"}</Button>}>
                  <Input placeholder="请输入短信验证码"></Input>
               </Form.Item>
               <Form.Item>
                  <Button block type="submit" loading={loading}>登录</Button>
               </Form.Item>
            </Form>
         </div>
      </div>
   );
};

export default Login;
